package com.srwl.mytx.im.conversation;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ConversationActivity.SystemNotifyActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.ConversationData;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.MessageHandler;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.PreferenceManager;

import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 系统推送消息会话
 */
public class SystemNotifyConversation extends Conversation {
    private static final String TAG = "SystemMessageConversati";
    private boolean asyncUserInfo;
    protected Context context;
    protected LocalBroadcastManager broadcastManager;
    private SystemNotifyListener systemNotifyListener;
    public SystemNotifyConversation() {
    }

    public SystemNotifyConversation(Context context, ConversationData data, MessageHandler messageHandler, MessageUnReadCountListener unReadCountListener) {
        this.context = context;
        this.data = data;
        this.messageHandler = messageHandler;
        this.unReadCountListener = unReadCountListener;

        cId = data.getCId();
        this.type = data.getType();
        unReadCount = data.getUnReadCount();

        conversationDataDao = DBManager.getInstance().getDaoSession().getConversationDataDao();
        queryUnReadCount();
        loadLastMessage();
        broadcastManager = LocalBroadcastManager.getInstance(context);
    }


    @Override
    public void receivedMessage(Message message) {
        Integer subType = message.getSubType();
        switch (subType) {
            case Constant.PUSH_MESSAGE_PERSON_RECEIVED_FORWARD:
                Log.i(TAG, "receivedMessage: 收到转发捐赠");
                syncUserInfo();
                saveMessageAndRefreshView(message);
                break;
            case Constant.PUSH_MESSAGE_PERSON_RECEIVED_DONATION:
                Log.i(TAG, "receivedMessage: 收到个人捐赠");
                syncUserInfo();
                saveMessageAndRefreshView(message);
                break;
            case Constant.PUSH_MESSAGE_TOPIC_VERIFY:
                Log.i(TAG, "receivedMessage:主题审核推送消息");
                // JSONObject topicJSON = JSONObject.parseObject(message.getExtraData());
//                String topicId = topicJSON.getString("id");
//                message.setId(topicId);
                saveMessageAndRefreshView(message);
                break;

            case Constant.PUSH_MESSAGE_APPLY_WITHDRAW:
            case Constant.PUSH_MESSAGE_WITHDRAW_COMPLETE:
                Log.i(TAG, "receivedMessage: 收到提现推送消息");
                saveMessageAndRefreshView(message);
                break;
            case Constant.PUSH_MESSAGE_SYSTEM_MESSAGE:
                Log.i(TAG, "receivedMessage: 收到通用系统推送消息");
                saveMessageAndRefreshView(message);
            case Constant.PUSH_MESSAGE_SYNC_USER_INFO:
                Log.i(TAG, "receivedMessage: 收到同步用户信息的推送消息");
                syncUserInfo();
                break;
            case Constant.PUSH_MESSAGE_NEW_TOPIC:
                Log.d(TAG, "onPushMessage: 收到周边新主题的推送消息");
                onReceiveNewTopic(message);
                break;

            case Constant.PUSH_MESSAGE_FOUND_COUPON:
                Log.d(TAG, "onPushMessage: 收到周边红包推送信息");
                Topic couponTopic = JSONObject.parseObject(message.getExtraData(), Topic.class);
                Intent intent1 = new Intent(Constant.ACTION_FOUND_COUPON);
                intent1.putExtra(Constant.EXTRA_INFO_TOPIC, couponTopic);
                broadcastManager.sendBroadcast(intent1);
                break;
            case Constant.PUSH_MESSAGE_LIVE_ACCUSATION:
                Log.i(TAG, "receivedMessage: 收到直播间内容举报消息");
                saveMessageAndRefreshView(message);
                break;
            case Constant.PUSH_MESSAGE_LIVE_ERROR_REPORT:
                Log.i(TAG, "receivedMessage: 收到直播间错误报告消息");
                saveMessageAndRefreshView(message);
                break;
            default:
                Log.e(TAG, "receivedMessage: 有消息类型没有处理" + message.toString());
        }
    }


    /**
     * 把消息保存在本地数据库，并根据是否是否打开会话页面 和页面是否在后台，响铃等
     * 通知会话刷新
     *
     * @param message
     */
    protected void saveMessageAndRefreshView(Message message) {
        message.setcId(cId);
        lastMessage = message;
        if (messageListener != null) {
            messageListener.onReceiveMessage(message);
            message.setReadState(Constant.MESSAGE_READ_STATE_READ);//设置该消息为 已读状态
            messageHandler.saveMessage(message);
            //判断会话页面是否是在后台，应该响铃
            if (isActivityInBackstage) {
                messageHandler.vibrateAndPlayTone();
            }
        } else {
            //消息监听为空，说明没有在会话详情页面，需要响铃，并且重读消息未读数
            messageHandler.vibrateAndPlayTone();
            message.setReadState(Constant.MESSAGE_READ_STATE_UNREAD);//设置该消息为 未读状态
            //必须先保存，再读取未读数
            messageHandler.saveMessage(message);
            queryUnReadCount();
        }

        //如果是临时会话，说明此刻会话没有显示到会话列表中，需要添加进会话列表
        if (isTempConversation) {
            setTempConversation(false);
            if (conversationListener != null) {
                conversationListener.onConversationAdd(this);
            }
        } else {//不是临时会话，那刷新
            if (conversationListener != null) {
                conversationListener.onMessageChange(this);
            }
        }
        data.setUpdated(new Date());//设置更新时间，用于从数据库加载会话列表的时候，按更新时间排序
        saveData();
    }

    private void onReceiveNewTopic(Message notify) {
        Topic newTopic = JSONObject.parseObject(notify.getExtraData(), Topic.class);
        Intent intent1 = new Intent(Constant.ACTION_NEW_COUPON);
        intent1.putExtra(Constant.EXTRA_INFO_TOPIC, newTopic);
        broadcastManager.sendBroadcast(intent1);
    }

    /**
     * 系统推送消息未读数，以消息表中查询出来的数量为准，而不是 ConversationData 中记录的未读数
     * 因为推送消息存在覆盖的问题，比如同一个人发送的添加联系人请求，就算重复发送，在message 中，也只会存在一条数据，
     */
    protected void queryUnReadCount() {
        //每次保存消息后，都重新读取通知类型的消息未读数量，因为推送类型的消息id,可能是重复的（比如和某一个人的添加联系人相关的消息或者是某个悬赏主题的任务通知消息），
        // 也许某条信息还是未读状态，就被覆盖了，只有去数据库读取未读数，才能保证正确的通知类型消息的未读总数
        int newUnReadCount = messageHandler.queryUnreadCount(cId);
        if (newUnReadCount > unReadCount && unReadCountListener != null) {
            unReadCountListener.onReadCountAdd(newUnReadCount - unReadCount);
            Log.d(TAG, "saveNotify: 系统推送消息未读数增加" + (newUnReadCount - unReadCount));
            unReadCount = newUnReadCount;
        } else if (newUnReadCount < unReadCount && unReadCountListener != null) {
            unReadCountListener.onReadCountReduce(unReadCount - newUnReadCount);
            Log.d(TAG, "saveNotify: 系统推送消息未读数减少" + (unReadCount - newUnReadCount));
            unReadCount = newUnReadCount;
        }
    }

    /**
     * 同步用户数据
     */
    protected void syncUserInfo() {
        //后对对更新用户信息的消息做了离线消息处理，可能出现用户掉线重连或者登录后同时出现多条 更新用户数据的消息，所以这样加一个判断
        if (asyncUserInfo) {
            return;
        }
        asyncUserInfo = true;
        JSONObject body = new JSONObject();
        body.put("token", PreferenceManager.getInstance().getCurrentUserToken());
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .syncUserInfo(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        asyncUserInfo = false;
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "同步用户信息失败:" + response.message());
                            return;
                        }
                        if (commonResult.isOK()) {
                            Log.i(TAG, "同步用户信息完成");
                            JSONObject data = (JSONObject) commonResult.getData();
                            final User user = data.getObject("userInfo", User.class);
                            //保存登录用户个人信息
                            UserProfileManager.getInstance().syncLoginUserInfo(user);
                            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_USER_INFO_CHANGE));
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        asyncUserInfo = false;
                        Log.e(TAG, "同步用户信息失败:" + t.getMessage());
                    }
                });

    }

    public String getTitle() {
        return "系统通知";
    }

    @Override
    public int getIconResourceId() {
        return R.drawable.mytx_icon_3;
    }

    public String getContent() {
        if (lastMessage == null) {
            return "";
        }

        return lastMessage.getContent();
    }

    /**
     * 打开通知页面
     *
     * @param context
     */
    public void openConversation(Context context) {
        //设置系统通知消息未读数为0
        if (unReadCount > 0) {
            if (unReadCountListener != null) {
                unReadCountListener.onReadCountReduce(unReadCount);
            }
            messageHandler.setMessageReadByConversationId(cId);
            unReadCount = 0;
        }
        context.startActivity(new Intent(context, SystemNotifyActivity.class));
    }

    @Override
    public void clear() {
        super.clear();
        systemNotifyListener = null;
    }

    public void messageChange(Message notify) {
        if (systemNotifyListener != null) {
            systemNotifyListener.onMessageChange(notify);
        }
    }

    public void setSystemNotifyListener(SystemNotifyListener systemNotifyListener) {
        this.systemNotifyListener = systemNotifyListener;
    }

    public interface SystemNotifyListener {
        void onMessageChange(Message notify);
    }

}
